﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using shop.Bll;
using shop.Model;

namespace shop.Web.PlanTask
{

    /// <summary> 自动同步出库信息 </summary>
    public class SyncStockoutJob : IJob
    {
        static IScheduler scheduler;

        private NLog.Logger _logger = NLog.LogManager.GetLogger("SyncStockoutJob");



        public DateTime MinDate { set; get; }


        /// <summary> job接口 </summary>
        public async Task Execute(IJobExecutionContext context)
        {
            MinDate = new DateTime(2023, 5, 26);
            var maxTime = DateTime.Now.AddHours(-1);

            //目前数据库最后一次出库记录的时间
            try
            {
                maxTime = await DB.FSql
                   .Select<tradeItem>()
                   .MaxAsync(a => a.consign_time);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);

                //throw;
            }
       

            var begin = (MinDate > maxTime ? MinDate : maxTime);
            var endMax = DateTime.Now.AddMinutes(-10);
            var end = endMax;



            // https://open.wangdian.cn/qyb/open/apidoc/doc?path=stockout_order_query_trade.php

            while (true)
            {
                //一次最大30天的范围
                if ((end-begin).TotalDays>30)
                {
                    end = begin.AddDays(29);
                }

                var page_no = 1;

                while (true)
                {
                    var res = await new WdtApi("stockout_order_query_trade.php")
                        .AddParam("start_time", begin.ToString("yyyy-MM-dd HH:mm:ss"))
                        .AddParam("end_time", end.ToString("yyyy-MM-dd HH:mm:ss"))
                        .AddParam("page_size", "100")
                        .AddParam("page_no", page_no.ToString())
                        .AddParam("is_no_position", "1")  //货位节点校验：0：返回position_list节点数据   1：不返回position_list节点数据，默认为0
                        .Post<shop.Model.stockout_order_query_tradeResult>();

                    if (res.stockout_list == null || res.stockout_list.Count == 0)
                    {
                        //退出循环
                        break;
                    }

                    //
                    await DB.FSql.Insert(res.stockout_list).ExecuteAffrowsAsync();

                    //货品列表节点
                    var gList = res.stockout_list
                        .SelectMany(c => c.details_list)
                        .ToList();

                    await DB.FSql.Insert(gList).ExecuteAffrowsAsync();

                    page_no++;
                }

                if (end >= endMax)
                {
                    break;
                }

                begin = end;
                end = endMax;
            }


            //检查是否有重复的id
            var repeat = await DB.FSql.Select<stockout_order_query_tradeItem>()
                .GroupBy(a => a.stockout_id)
                .Having(a => a.Count(a.Key) > 1)
                .ToListAsync(a => new
                {
                    a.Key,
                    minId = a.Min(a.Value.id)
                });

            //删除重复
            foreach (var item in repeat)
            {
                await DB.FSql.Delete<stockout_order_query_tradeItem>()
                    .Where(a => a.id == item.minId)
                    .ExecuteAffrowsAsync();
            }


        }



        /// <summary>  </summary>
        public static async void CreatePlanJob()
        {

            scheduler?.Clear();


            //1、创建一个调度器
            var factory = new StdSchedulerFactory();
            scheduler = await factory.GetScheduler();
            await scheduler.Start();

            //2、创建一个任务
            IJobDetail job = JobBuilder.Create<SyncStockoutJob>().WithIdentity(nameof(SyncStockoutJob), "group1").Build();

            //3、创建一个触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(nameof(SyncStockoutJob), "group1")
                .WithSimpleSchedule(x=> x
                    .WithIntervalInMinutes(3)  //每隔30分钟
                    .RepeatForever()            //永远重复
                    )
                ////秒 分 时 某一天 月 周 年(可选参数)
                //.WithCronSchedule($"0 {5} * * * ?")     //Cron语法
                //.StartAt(runTime)
                .StartNow()
                .Build();

            //4、将任务与触发器添加到调度器中
            await scheduler.ScheduleJob(job, trigger);


            //5、开始执行
            await scheduler.Start();

        }


    }
}
